import sqlite3
import time
from datetime import datetime

from selenium.webdriver import Chrome, Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "localhost:9222")
driver = Chrome(
    service=Service(r'C:\Users\Administrator\.cache\selenium\chromedriver\win64\129.0.6668.70\chromedriver.exe'),
    options=chrome_options)

conn = sqlite3.connect('E:\sqlite\GooglePlayAppsLink.db')
cursor = conn.cursor()
# 注意：把chromedriver文件放到了当前文件夹里面，可以这样调用
# driver = Chrome('./chromedriver.exe', options=chrome_options)
# driver.get("https://www.baidu.com")



def get_duns():
    try:
        element = driver.find_element(by=By.CLASS_NAME,value="ant-table-tbody")
    except:
        time.sleep(10)
        element = driver.find_element(by=By.CLASS_NAME,value="ant-table-tbody")

        pass
    rows = element.find_elements(by=By.TAG_NAME,value="tr")
    for row in rows:
        a = ''
        cells = row.find_elements(by=By.TAG_NAME,value="td")
        for cell in cells:
            a = a+cell.text+'|'
            # print(cell.text, end="\t")  # 使用\t作为列分隔符

        split = a.split("|")
        if split[1] == '':
            pass
        try:

            now = datetime.now()
            formatted_now = now.strftime('%Y-%m-%d %H:%M:%S')
            s = str(split[3])
            domain_ = s[s.find('.')+1:]
            cursor.execute(
                'INSERT INTO duns (name, duns,url,address1,address2,city,state,country,postal_code,contacts_number,insert_time,domain) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)',
                (split[1], split[2].strip(), split[3], split[4], split[5],split[6],split[7],split[8],split[9],split[10],now,domain_))
            conn.commit()
        except Exception as e:
            print(e)
            pass
        print(a)  # 换行，表示一行结束

# i = 326
# i = 245
# i = 194
# i = 365 UK
# i = 234 CN
i = 1
driver.switch_to.window(driver.window_handles[0])#浏览器对象切换到最新窗口

while True:
    # driver.get("http://www.baidu.com")
    print(driver.title)
    print(str(i)+"---------------------------------------------------")
    element = driver.find_element(by=By.CLASS_NAME,value="ant-input-number-input")
    element.send_keys(Keys.CONTROL+"a")
    element.send_keys(Keys.DELETE)
    element.send_keys(i)
    time.sleep(2)
    element.send_keys(Keys.ENTER)
    time.sleep(8)
    i = i+1
    get_duns()
    time.sleep(10)


